package plugins.septwolves;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import com.meiya.common.string.StringUtil;
import com.zhangwoo.spider.client.process.AnalyserTemplate;
import com.zhangwoo.spider.po.Conversation;
import com.zhangwoo.spider.po.UrlRequest;

/**
 * 采集商品
 *
 */
public class SeptwolvesTmallItem implements AnalyserTemplate {
	Logger logger = Logger.getLogger(this.getClass().getName());

	public boolean isMatchTemplate(UrlRequest urlReq, String html) {
		if(urlReq.getUrl().indexOf("http://septwolves.tmall.com")!=-1)
			return true;
		return false;
	}

	public List<Conversation> findConversations(UrlRequest urlReq, String html,
			Document docHtml) {
		List<Conversation> convsResults = new ArrayList<Conversation>();
		return convsResults;
	}

	public List<UrlRequest> findLinks(UrlRequest urlReq, String html,
			Document docHtml) {
		List<UrlRequest> links = new ArrayList<UrlRequest>();
		String expItem="<a class=\"item-name\".*?href=\"http://detail\\.tmall\\.com/item\\.htm[^\"]*id=(\\d+)&[^\"]*\".*?>([^<]*?)</a>";
		String expPage="href=\"(http://septwolves.tmall.com/category.htm[^\"]*pageNo=\\d+#anchor)\"";
		List<String[]> r= StringUtil.matchAll(html, expItem);
		try {
			for(String[] o : r){
				UrlRequest u = (UrlRequest) urlReq.clone();
				u.setUrl("http://rate.tmall.com/list_detail_rate.htm?itemId="+o[1]+"&order=0&currentPage=1&append=0&content=0");
				u.setTitle(o[2]);
				if(!links.contains(u))	links.add(u);
			}

			r= StringUtil.matchAll(html, expPage);
			for(String[] o : r){
				UrlRequest u = (UrlRequest) urlReq.clone();
				u.setUrl(o[1]);
				if(!links.contains(u))	links.add(u);
			}
		} catch (Exception e) {
			logger.error("SeptwolvesTmallItem error",e);
		}
		return links;
	}
}
